package com.walking.shopportal.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author walking
 * 公众号编程大道
 */
@RestController
public class BuyControllerV1 {
    /**
     * 服务发现客户端
     */
    @Autowired
    private DiscoveryClient client;
    /**
     * http调用工具，类似httpclient
     */
    @Autowired
    @Qualifier("restTemplateV1")
    private RestTemplate restTemplate;

    /**
     * RestTemplate方式调用微服务，需要获取服务列表，自己选一个服务地址进行调用
     *
     * @return
     */
    @GetMapping("/buy/{productId}")
    public Map<String, Object> buy(@PathVariable String productId) {
        // 获取订单服务地址列表 自己写逻辑用于选取一个地址
        List<ServiceInstance> list = this.client.getInstances("order-service");
        String uri = "";
        for (ServiceInstance instance : list) {
            if (instance.getUri() != null && !"".equals(instance.getUri())) {
                uri = instance.getUri().toString();
                break;
            }
        }
        // 微服务调用 调下单接口
        Map result = restTemplate.postForObject(uri + "/order/create/{productId}", null,
                Map.class, productId);

        Map<String, Object> response = new HashMap<String, Object>();
        response.put("response", result);
        return response;
    }
}
